package com.shekhar.paas.web;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.shekhar.paas.domain.Story;
import com.shekhar.paas.story.StoryService;

@Controller
@RequestMapping(value = "/stories")
public class StoryController {

    private Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    private StoryService storyService;

    @RequestMapping(produces = "text/html")
    public String listStoriesByDateDesc(@RequestParam(value = "page", required = false) Integer page,
            @RequestParam(value = "size", required = false) Integer size,
            Model uiModel) {
        int sizeNo = size == null ? 10 : size.intValue();
        List<Story> stories = new ArrayList<Story>();
        if (page != null || size != null) {
            final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
            stories = storyService.findAllStoriesByDateDesc(firstResult, sizeNo);
        } else {
            stories = storyService.findAllStoriesByDateDesc(0, 20);
        }
        uiModel.addAttribute("stories", stories);
        float nrOfPages = (float) storyService.countAllStories() / sizeNo;
        uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
        addDateTimeFormatPatterns(uiModel);
        return "stories/list";
    }

    @RequestMapping(value = "/{tag}",method = RequestMethod.GET, produces = "text/html")
    public String listStoriesByPaasProvider(@PathVariable("tag") String tag,Model uiModel) {
        List<Story> topTenStoriesByTag = storyService.findTopTenStoriesByTag(tag);
        if(CollectionUtils.isEmpty(topTenStoriesByTag) || topTenStoriesByTag.size() < 10){
            topTenStoriesByTag = storyService.findTopTenStoriesByTagInLast24Hours(tag);
        }
        uiModel.addAttribute("stories", topTenStoriesByTag);
        return "stories/list";
    }

    void addDateTimeFormatPatterns(Model uiModel) {
        uiModel.addAttribute("story_creationDate_date_format", DateTimeFormat.patternForStyle("M-", LocaleContextHolder.getLocale()));
    }
}
